package socket;

//去除关闭后的异常
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class CharClient extends Frame {

	TextField tf = new TextField();
	TextArea ta = new TextArea();
	Socket s = null;	
	DataOutputStream dos = null;	
	DataInputStream dis = null;
	private boolean bConnected = false;
	
	public static void main(String[] args) {
		new CharClient().MyFrame();
	}

	public void MyFrame() {
		setBounds(300, 300, 400, 400);
		add(tf, BorderLayout.SOUTH);
		add(ta, BorderLayout.NORTH);
		pack();
		tf.addActionListener(new TFListener());		
		setVisible(true);
		connect();
		new Thread(new RecThread()).start();
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				disconnect();
				System.exit(0);
			}
		});
		
		}
	
	public void connect(){
		try {
			s = new Socket("127.0.0.1",8888);
			dos = new DataOutputStream(s.getOutputStream());
			dis = new DataInputStream (s.getInputStream());
			bConnected = true;
			} catch (UnknownHostException e) {
			e.printStackTrace();
			} catch (IOException e) {
			e.printStackTrace();
			}
		}
	public void disconnect(){
		try{
		dos.close();
		dis.close();
		s.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	private class TFListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			String str = tf.getText();
			//ta.setText(str);
			tf.setText(""); 
			try{		
				dos.writeUTF(str);
				dos.flush();
			}catch(IOException ex){
				ex.printStackTrace();
			}
			
		}
	}
	private class RecThread implements Runnable{
		public void run(){
			try{
				while(bConnected){
				String str = dis.readUTF();
				ta.setText(ta.getText() + str + '\n');
			}
			}catch(SocketException e){
				System.out.println("program end!");
			}
			catch(IOException e){
				e.printStackTrace();
			}
		}
	}
}

